package com.quanxi.qxaimain.common.ThreadPoolTaskExecutor;

import com.quanxi.qxaimain.service.indicatorsService.indicatorsAsynServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author lyx
 * @create 2020/10/15 11:45
 * 线程池配置
 *
 */
@Slf4j
@Configuration
@EnableAsync
public class TaskPoolConfig implements AsyncConfigurer {
    private static final Logger LOG = LoggerFactory.getLogger(indicatorsAsynServiceImpl.class);
    @Bean("taskExecutor")
    public Executor taskExecutro(){
        LOG.info("start thread taskExecutor 线程设置：");
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        int core = Runtime.getRuntime().availableProcessors();//此方法返回可用处理器的虚拟机的最大数量; 不小于1
     //   core=2;
        log.info("可用处理器的虚拟机的最大数量:"+core);
        taskExecutor.setCorePoolSize(core);//设置核心线程数
        taskExecutor.setMaxPoolSize(core+1);//设置最大线程数 CPU密集型：N+1，避免缺页中断导致处理器资源浪费，可设置一个额外的线程；
        int num=core+1;
        LOG.info("设置最大线程数："+num);
      //  taskExecutor.setMaxPoolSize(core*2);//设置最大线程数
        taskExecutor.setQueueCapacity(40);//如果传入值大于0，底层队列使用的是LinkedBlockingQueue,否则默认使用SynchronousQueue
        taskExecutor.setKeepAliveSeconds(30);//除核心线程外的线程存活时间
        taskExecutor.setThreadNamePrefix("thread-taskExecutor");//线程名称前缀
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//设置拒绝策略
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        taskExecutor.setAwaitTerminationSeconds(60);//设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住。
        return taskExecutor;
}

    /**
     * 异步异常处理
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }

}